import echarts from "@/plugins/echarts.plugin";
import { useAppSelector } from "@/store/hooks";
import React, { useEffect, useRef, useState } from "react";

interface PropsInt {
  options: any;
}

export default function Chart(prop: PropsInt) {
  const currentTheme = useAppSelector((state) => state.app.theme);
  const [height, setheight] = useState("");
  const [chartInstance, setchartInstance] = useState<echarts.ECharts | null>(
    null
  );
  const chartInnerRef = React.createRef<HTMLDivElement>();
  const chartContainerRef = useRef<HTMLDivElement>();

  const onResize = () => {
    if (chartInstance) {
      getHeight();
    }
  };

  const getHeight = () => {
    const height = Math.floor(
      chartContainerRef.current?.getBoundingClientRect().height || 0
    );
    console.log("----", height);

    setheight(height + "px");
  };

  useEffect(() => {
    if (chartContainerRef.current) {
      getHeight();
    }
  }, [chartContainerRef]);

  useEffect(() => {
    if (height && chartInnerRef.current && !chartInstance) {
      const chartInstance = echarts.init(chartInnerRef.current);
      chartInstance.setOption(prop.options);
      setchartInstance(chartInstance);
    } else {
      if (chartInstance) {
        chartInstance.resize();
      }
    }
  }, [height, chartInnerRef, chartInstance]);

  useEffect(() => {
    chartInstance && window.addEventListener("resize", onResize);
  }, [chartInstance]);

  useEffect(() => {
    chartInstance?.setOption(prop.options);
  }, [prop.options]);

  useEffect(() => {
    if (currentTheme) {
      chartInstance?.dispose();
      const newChartInstance = echarts.init(
        chartInnerRef.current,
        currentTheme?.key
      );
      newChartInstance.setOption(prop.options);
      setchartInstance(newChartInstance);
    }
  }, [currentTheme]);

  useEffect(() => {
    return () => {
      chartInstance?.dispose();
      window.removeEventListener("resize", onResize);
    };
  }, []);

  return (
    <div ref={chartContainerRef} className="chart-container w-full h-full">
      <div
        style={{ height }}
        className="chart-inner w-full"
        ref={chartInnerRef}
      ></div>
    </div>
  );
}
